<template>
  <div class="root-container" v-loading.fullscreen.lock="isLoading">
    <div class="card-header-container">
      <span class="card-title">
        <span>CEM</span>
        <el-icon><ArrowRightBold /></el-icon>
        <span>扇区方案设置</span>
      </span>
      <span>
        <el-button
          type="primary"
          link
          :disabled="!isValid"
          @click="handleSave()"
        >
          <el-icon><UploadFilled /></el-icon>
          <span>保存</span>
        </el-button>
        <el-button type="warning" link @click="handleReset()">
          <el-icon><RefreshLeft /></el-icon>
          <span>清空</span>
        </el-button>
        <el-button
          type="danger"
          link
          :disabled="formData.number == -1"
          @click="handleDelete()"
        >
          <el-icon><DeleteFilled /></el-icon>
          <span>删除</span>
        </el-button>
      </span>
    </div>
    <div class="card-content-container">
      <el-row :gutter="20">
        <el-col :xs="24" :sm="12" :md="8" :lg="5">
          <el-scrollbar :height="contentHeight">
            <div
              class="card-subitem-container border-right"
              :style="{ minHeight: contentHeight }"
            >
              <el-text
                v-if="CEMStore.sectors.length == 0"
                type="info"
                size="small"
              >
                <el-icon><InfoFilled /></el-icon>
                <span style="padding-left: 6px">未找到已保存的扇区方案</span>
              </el-text>
              <!-- <el-button
                v-for="(item, index) in CEMStore.sectors"
                class="area-item-button"
                type="primary"
                size="small"
                :text="formData.number != item.number"
                @click="handleSelect(index)"
              >
                <span>{{ item.title }}</span>
              </el-button> -->
              <div
                v-for="(item, index) in CEMStore.sectors"
                :class="[
                  'area-item-option',
                  formData.number == item.number
                    ? 'area-item-option-selected'
                    : 'area-item-option-unselected',
                ]"
                @click="handleSelect(index)"
              >
                <span>{{ item.title }}</span>
              </div>
            </div>
          </el-scrollbar>
        </el-col>
        <el-col :xs="24" :sm="12" :md="16" :lg="19">
          <el-scrollbar :height="contentHeight">
            <div
              class="card-subitem-container page-container"
              :style="{ minHeight: contentHeight }"
            >
              <el-form label-width="70" size="small">
                <el-form-item label="方案名称">
                  <div class="form-item-container">
                    <el-input v-model="formData.title"></el-input>
                    <el-tag v-if="formData.title.length == 0" type="danger">
                      必填
                    </el-tag>
                    <el-tag v-if="isTitleDuplicate" type="danger"
                      >名称重复</el-tag
                    >
                  </div>
                </el-form-item>
                <el-form-item label="描述信息">
                  <div class="form-item-container">
                    <el-input v-model="formData.description"></el-input>
                    <!-- <el-tag>可选</el-tag> -->
                  </div>
                </el-form-item>
                <el-form-item label="适用模式">
                  <div class="form-item-container">
                    <el-tag v-for="item in selectedModes" class="tag-small">{{
                      item
                    }}</el-tag>
                    <el-text v-if="selectedModes.length == 0" type="danger">
                      <el-icon><CircleCloseFilled /></el-icon>
                      <span>&nbsp;Emm...&emsp;&emsp;/ᐠ｡ꞈ｡ᐟ\</span>
                      <!-- <span>Error</span> -->
                    </el-text>
                  </div>
                </el-form-item>
                <el-form-item label="物理模块">
                  <el-tag
                    v-for="item in modelInfo.selected"
                    :type="modelInfo.duplicated.includes(item) ? 'warning' : ''"
                    class="tag-small"
                  >
                    <span>{{ item }}</span>
                  </el-tag>
                  <el-tag
                    v-for="item in modelInfo.lack"
                    type="danger"
                    class="tag-small"
                  >
                    <span>{{ item }}</span>
                  </el-tag>
                </el-form-item>
                <el-form-item>
                  <template #label>
                    <div style="width: 100%; text-align: right">
                      <div>空域组合</div>
                      <div>(已选:&nbsp;{{ selectedAreas.length }})</div>
                      <div>
                        <el-button
                          v-if="selectedAreas.length > 0"
                          type="danger"
                          link
                          @click="handleClear()"
                        >
                          <el-icon> <DocumentDelete /> </el-icon>
                          <span>清空</span>
                        </el-button>
                      </div>
                    </div>
                  </template>
                  <!-- <el-cascader
              v-model="formData.areas"
              :options="areaOptions"
              :props="{ multiple: true }"
            /> -->
                  <div class="form-item-container">
                    <div class="input-wrapper">
                      <el-scrollbar max-height="calc(100vh - 452px)">
                        <div style="padding: 12px 0 12px 12px">
                          <el-checkbox-group v-model="formData.areas">
                            <el-checkbox
                              v-for="item in CEMStore.areas"
                              :label="item.identifier"
                              style="display: block"
                            >
                              <div class="flex-line">
                                <el-text
                                  :type="
                                    item.modes.includes('NN') ||
                                    item.modes.includes('NNWJ')
                                      ? 'primary'
                                      : item.modes.includes('SS') ||
                                        item.modes.includes('SSWJ')
                                      ? 'warning'
                                      : 'danger'
                                  "
                                >
                                  {{ item.modes.join(", ") }}
                                </el-text>
                                <el-icon style="margin: 0 6px"
                                  ><ArrowRightBold
                                /></el-icon>
                                <el-text
                                  :type="
                                    item.models.includes('AP01') &&
                                    item.models.includes('AP12')
                                      ? 'info'
                                      : item.models.includes('AP01')
                                      ? 'primary'
                                      : item.models.includes('AP12')
                                      ? 'success'
                                      : item.models.includes('AP81') ||
                                        item.models.includes('AP81')
                                      ? 'danger'
                                      : item.models.includes('AP7C') ||
                                        item.models.includes('APC7')
                                      ? 'warning'
                                      : ''
                                  "
                                  >{{ item.models.join(", ") }}</el-text
                                >
                              </div>
                            </el-checkbox>
                          </el-checkbox-group>
                        </div>
                      </el-scrollbar>
                    </div>
                  </div>
                </el-form-item>
              </el-form>
            </div>
          </el-scrollbar>
        </el-col>
      </el-row>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted, onUnmounted } from "vue";
import { ElMessage, ElMessageBox, ElNotification } from "element-plus";
import axios from "axios";
import dayjs from "dayjs";

import useFlowStore from "@/store/flow.js";
import useCommonStore from "@/store/common.js";
import useCEMStore from "@/store/CEM.js";

import params from "../common/params.json";

const flowStore = useFlowStore();
const commonStore = useCommonStore();
const CEMStore = useCEMStore();

const isLoading = ref(false);

const formData = ref({
  number: -1,
  title: "",
  description: "",
  modes: [],
  areas: [],
  areaCount: 0,
  createTime: "",
  status: 1,
});

const areaOptions = computed(() =>
  CEMStore.areas.map((area) => ({
    label: area.identifier,
    value: area.identifier,
  }))
);

const intersection = (a, b) => a.filter((x) => b.includes(x));
const duplicates = (arr) =>
  arr.filter(
    (e, i) => arr.indexOf(e) !== arr.lastIndexOf(e) && arr.indexOf(e) === i
  );
const deduplicate = (arr) => Array.from(new Set(arr));

const selectedModes = computed(() => {
  if (formData.value.areas.length > 0) {
    let sourceModes = new Array();
    formData.value.areas.forEach((item) => {
      let targetModes = CEMStore.areas.filter(
        (area) => area.identifier == item
      )[0].modes;
      if (sourceModes.length == 0) {
        sourceModes = targetModes;
      } else {
        sourceModes = intersection(sourceModes, targetModes);
      }
    });
    return sourceModes;
  } else {
    return new Array();
  }
});

const selectedAreas = computed(() =>
  CEMStore.areas.filter((area) =>
    formData.value.areas.includes(area.identifier)
  )
);

const modelInfo = computed(() => {
  let areas = selectedAreas.value;
  let models = [];
  areas.forEach((area) => models.push(...area.models));
  let duplicated = duplicates(models);
  let selected = deduplicate(models);
  let lack = params.models.filter((model) => !selected.includes(model));
  selected.sort();
  duplicated.sort();
  lack.sort();
  return {
    selected,
    duplicated,
    lack,
  };
});

const isTitleDuplicate = computed(
  () =>
    formData.value.number == -1 &&
    CEMStore.sectors.filter((sector) => sector.title == formData.value.title)
      .length > 0
);

const isValid = computed(
  () =>
    modelInfo.value.lack.length === 0 &&
    modelInfo.value.duplicated.length === 0 &&
    selectedModes.value.length > 0 &&
    formData.value.title.length > 0 &&
    !isTitleDuplicate.value
);

const handleReset = () => {
  formData.value = {
    number: -1,
    title: "",
    description: "",
    modes: [],
    areas: [],
  };
};

const handleClear = () => {
  formData.value.areas = [];
};

const handleSelect = (index) => {
  formData.value = JSON.parse(JSON.stringify(CEMStore.sectors[index]));
};

const handleSave = async () => {
  isLoading.value = true;
  formData.value.modes = selectedModes.value;
  formData.value.areaCount = formData.value.areas.length;
  formData.value.createTime = dayjs().format("YYYY-MM-DD HH:mm:ss");
  formData.value.status = 1;
  await CEMStore.saveSector(formData.value);
  // handleReset();
  isLoading.value = false;
};

const handleDelete = async () => {
  isLoading.value = true;
  await CEMStore.deleteSector(formData.value);
  handleReset();
  isLoading.value = false;
};

const contentHeight = computed(() => commonStore.clientHeight - 199 + "px");

onMounted(() => {
  handleReset();
});
</script>

<style scoped>
@import "../common/card.css";
</style>
